<?php

namespace App\Console\Commands\Command;

use App\Models\Common\Area\Area;
use App\Models\Common\Area\Repositories\AreaRepository;
use App\Models\Common\Area\Repositories\Interfaces\AreaRepositoryInterface;
use App\Trip\Geo\Amap\District;
use Overtrue\LaravelPinyin\Facades\Pinyin;

class UpdateAreas
{
    public static function fetchAll(): bool
    {
        $geoLib    = new District();
        $districts = $geoLib->districts('', 3);
        static::update($districts, 0);
        return true;
    }

    private static function update(array $districts, int $parent_code = 0): void
    {
        /**
         * @var AreaRepository $areaRepo
         */
        $areaRepo = app()->make(AreaRepositoryInterface::class);
        foreach ($districts as $district) {
            // 只录入省市区
            if (!in_array($district['level'], Area::SUPPORT_LEVELS)) {
                continue;
            }


            $data = [
                'citycode'    => is_array($district['citycode']) ? 0 : $district['citycode'],
                'adcode'      => $district['adcode'],
                'name'        => $district['name'],
                'level'       => $district['level'],
                'center'      => $district['center'] ?? '',
                'parent_code' => $parent_code,
                'letter'      => Pinyin::abbr($district['name'])[0] ?? '',
            ];

            if ($area = $areaRepo->findByCode($district['adcode'], true)) {
                $update = $areaRepo->updateArea($area, $data);
            } else {
                $area = $areaRepo->addArea($data);
            }


            if (empty($district['districts'])) {
                continue;
            }
            self::update($district['districts'], $district['adcode']);
        }
    }

}